<template>
  <div id="home-container">
    <navBox/>
    <div id="home-main" @scroll.passive="handleScroll">
      <router-view :name="$router.name"/>
      <footerPage/>
      <div id="backTop" v-if="showBack" @click="backTopHandle">
        <span class="icon el-icon-caret-top"></span>
        <span class="text">TOP</span>
      </div>
    </div>
  </div>
</template>

<script>
import navBox from "@/components/common/navBox.vue";
import footerPage from "@/components/common/footer.vue";
import bus from "@/bus/bus";

export default {
  name: "homePage",
  components: {navBox, footerPage},
  data() {
    return {
      showBack: false,
      isScrolling: false
    }
  },
  methods: {
    /**
     * 返回顶部
     */
    backTopHandle() {
      let top = document.getElementById('home-main').scrollTop
      // 实现滚动效果
      const timeTop = setInterval(() => {
        document.getElementById('home-main').scrollTop = top -= 50;
        if (top <= 0) {
          clearInterval(timeTop);
        }
      }, 10);
    },

    /**
     * 监听滚动 - 显示返回顶部按钮
     * @param e
     */
    async handleScroll(e) {
      // 使用节流来优化性能
      if (this.isScrolling) return;
      this.isScrolling = true;
      await this.$nextTick();
      this.isScrolling = false;
      e.target.scrollTop > 150 ? (this.showBack = true) : (this.showBack = false);

      const container = e.target;
      const SCROLL_THRESHOLD = 200;
      // 判断是否接近触底（距离底部200px）
      if (container.scrollHeight - (container.scrollTop + container.clientHeight) <= SCROLL_THRESHOLD) {
        // 通知注册了触底事件的页面
        switch (this.$route.path) {
          case '/mgHome': bus.$emit('homeHitBottom')
                break;
          case '/mineMg': bus.$emit('mineMgHitBottom')
                break;
        }
      }
    },
  },
  watch: {
    $route() {
      document.getElementById('home-main').scrollTop = 0
    }
  }
}
</script>

<style scoped lang="scss">
@import url("@/scss/home.scss");
</style>